//! API网关中间件系统
//!
//! 提供请求处理链和中间件管理

use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tower::{Layer, Service};
use axum::{
    http::{Request, Response, StatusCode, HeaderMap},
    body::Body,
};
use futures::future::BoxFuture;
use tracing::{info, warn, error};
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;

use base64::{Engine as _, engine::general_purpose};
use sha2::{Sha256, Digest};
use tokio::sync::RwLock;

/// 用户信息
#[derive(Debug, Clone)]
pub struct User {
    /// 用户ID
    pub id: String,
    /// 用户名
    pub username: String,
    /// 角色列表
    pub roles: Vec<String>,
    /// 权限列表
    pub permissions: Vec<String>,
}

/// 认证方式
#[derive(Debug, Clone)]
pub enum AuthMethod {
    /// API密钥认证
    ApiKey(String),
    /// Bearer Token认证
    BearerToken(String),
    /// 基础认证（用户名:密码）
    BasicAuth { username: String, password: String },
    /// JWT Token认证
    JwtToken(String),
}

/// 认证结果
#[derive(Debug, Clone)]
pub enum AuthResult {
    /// 认证成功
    Success(User),
    /// 认证失败
    Failed(String),
    /// 需要认证
    Required,
}

/// 权限检查结果
#[derive(Debug, Clone)]
pub enum AuthzResult {
    /// 授权成功
    Allowed,
    /// 授权失败
    Denied(String),
}

/// 认证授权提供者
pub trait AuthProvider: Send + Sync {
    /// 认证用户
    fn authenticate(&self, method: AuthMethod) -> BoxFuture<'_, AuthResult>;

    /// 检查权限
    fn authorize<'a>(&self, user: &'a User, resource: &str, action: &str) -> BoxFuture<'a, AuthzResult>;
}

/// 简单的内存认证提供者
#[derive(Debug, Clone)]
pub struct MemoryAuthProvider {
    /// API密钥到用户的映射
    api_keys: HashMap<String, User>,
    /// 用户名密码到用户的映射
    users: HashMap<String, (String, User)>, // username -> (password_hash, user)
}

impl MemoryAuthProvider {
    /// 创建新的内存认证提供者
    pub fn new() -> Self {
        let mut provider = Self {
            api_keys: HashMap::new(),
            users: HashMap::new(),
        };

        // 添加默认的管理员用户
        let admin_user = User {
            id: "admin".to_string(),
            username: "admin".to_string(),
            roles: vec!["admin".to_string()],
            permissions: vec!["*".to_string()], // 所有权限
        };

        // 添加默认API密钥
        provider.api_keys.insert("admin-key-123".to_string(), admin_user.clone());

        // 添加默认用户（密码：admin123）
        let password_hash = Self::hash_password("admin123");
        provider.users.insert("admin".to_string(), (password_hash, admin_user));

        provider
    }

    /// 添加API密钥
    pub fn add_api_key(&mut self, key: String, user: User) {
        self.api_keys.insert(key, user);
    }

    /// 添加用户
    pub fn add_user(&mut self, username: String, password: String, user: User) {
        let password_hash = Self::hash_password(&password);
        self.users.insert(username, (password_hash, user));
    }

    /// 哈希密码
    fn hash_password(password: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(password.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// 验证密码
    fn verify_password(password: &str, hash: &str) -> bool {
        Self::hash_password(password) == hash
    }
}

impl AuthProvider for MemoryAuthProvider {
    fn authenticate(&self, method: AuthMethod) -> BoxFuture<'_, AuthResult> {
        Box::pin(async move {
            match method {
                AuthMethod::ApiKey(key) => {
                    if let Some(user) = self.api_keys.get(&key) {
                        AuthResult::Success(user.clone())
                    } else {
                        AuthResult::Failed("无效的API密钥".to_string())
                    }
                }
                AuthMethod::BasicAuth { username, password } => {
                    if let Some((password_hash, user)) = self.users.get(&username) {
                        if Self::verify_password(&password, password_hash) {
                            AuthResult::Success(user.clone())
                        } else {
                            AuthResult::Failed("密码错误".to_string())
                        }
                    } else {
                        AuthResult::Failed("用户不存在".to_string())
                    }
                }
                AuthMethod::BearerToken(_) | AuthMethod::JwtToken(_) => {
                    // 简化实现，暂不支持
                    AuthResult::Failed("暂不支持此认证方式".to_string())
                }
            }
        })
    }

    fn authorize<'a>(&self, user: &'a User, _resource: &str, _action: &str) -> BoxFuture<'a, AuthzResult> {
        Box::pin(async move {
            // 简化实现：管理员拥有所有权限
            if user.roles.contains(&"admin".to_string()) || user.permissions.contains(&"*".to_string()) {
                AuthzResult::Allowed
            } else {
                AuthzResult::Denied("权限不足".to_string())
            }
        })
    }
}

/// 限流配置
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
    /// 每分钟最大请求数
    pub requests_per_minute: u32,
    /// 突发请求容量
    pub burst_capacity: u32,
    /// 限流窗口大小（秒）
    pub window_size: u64,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            requests_per_minute: 1000,
            burst_capacity: 100,
            window_size: 60,
        }
    }
}

/// 限流记录
#[derive(Debug, Clone)]
struct RateLimitRecord {
    /// 请求计数
    count: u32,
    /// 窗口开始时间
    window_start: Instant,
    /// 最后请求时间
    last_request: Instant,
}

/// 限流器
pub struct RateLimiter {
    /// 限流配置
    config: RateLimitConfig,
    /// 客户端限流记录
    records: Arc<RwLock<HashMap<String, RateLimitRecord>>>,
}

impl RateLimiter {
    /// 创建新的限流器
    pub fn new(config: RateLimitConfig) -> Self {
        Self {
            config,
            records: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 检查是否允许请求
    pub async fn is_allowed(&self, client_id: &str) -> bool {
        let mut records = self.records.write().await;
        let now = Instant::now();

        let record = records.entry(client_id.to_string()).or_insert_with(|| {
            RateLimitRecord {
                count: 0,
                window_start: now,
                last_request: now,
            }
        });

        // 检查是否需要重置窗口
        if now.duration_since(record.window_start).as_secs() >= self.config.window_size {
            record.count = 0;
            record.window_start = now;
        }

        // 检查是否超过限制
        if record.count >= self.config.requests_per_minute {
            // 检查突发容量
            if now.duration_since(record.last_request).as_secs() < 1 {
                return false;
            }
        }

        // 更新记录
        record.count += 1;
        record.last_request = now;

        true
    }

    /// 获取剩余请求数
    pub async fn remaining_requests(&self, client_id: &str) -> u32 {
        let records = self.records.read().await;
        if let Some(record) = records.get(client_id) {
            let now = Instant::now();
            if now.duration_since(record.window_start).as_secs() >= self.config.window_size {
                self.config.requests_per_minute
            } else {
                self.config.requests_per_minute.saturating_sub(record.count)
            }
        } else {
            self.config.requests_per_minute
        }
    }

    /// 清理过期记录
    pub async fn cleanup_expired(&self) {
        let mut records = self.records.write().await;
        let now = Instant::now();
        let cleanup_threshold = Duration::from_secs(self.config.window_size * 2);

        records.retain(|_, record| {
            now.duration_since(record.last_request) < cleanup_threshold
        });
    }
}

/// 中间件配置
pub struct MiddlewareConfig {
    /// 启用请求日志
    pub enable_logging: bool,
    /// 启用CORS
    pub enable_cors: bool,
    /// 启用认证
    pub enable_auth: bool,
    /// 启用限流
    pub enable_rate_limit: bool,
    /// 请求超时时间（秒）
    pub request_timeout: u64,
    /// 认证提供者
    pub auth_provider: Option<Arc<dyn AuthProvider>>,
    /// 限流配置
    pub rate_limit_config: Option<RateLimitConfig>,
}

impl Clone for MiddlewareConfig {
    fn clone(&self) -> Self {
        Self {
            enable_logging: self.enable_logging,
            enable_cors: self.enable_cors,
            enable_auth: self.enable_auth,
            enable_rate_limit: self.enable_rate_limit,
            request_timeout: self.request_timeout,
            auth_provider: self.auth_provider.clone(),
            rate_limit_config: self.rate_limit_config.clone(),
        }
    }
}

impl Default for MiddlewareConfig {
    fn default() -> Self {
        Self {
            enable_logging: true,
            enable_cors: true,
            enable_auth: false,
            enable_rate_limit: false,
            request_timeout: 30,
            auth_provider: None,
            rate_limit_config: None,
        }
    }
}

/// 中间件管理器
pub struct MiddlewareManager {
    config: MiddlewareConfig,
    rate_limiter: Option<RateLimiter>,
}

impl MiddlewareManager {
    /// 创建新的中间件管理器
    pub fn new(config: MiddlewareConfig) -> Self {
        let rate_limiter = if config.enable_rate_limit {
            config.rate_limit_config.as_ref().map(|cfg| RateLimiter::new(cfg.clone()))
        } else {
            None
        };

        Self {
            config,
            rate_limiter,
        }
    }

    /// 获取配置
    pub fn config(&self) -> &MiddlewareConfig {
        &self.config
    }

    /// 检查限流
    pub async fn check_rate_limit(&self, client_id: &str) -> Result<bool, String> {
        if !self.config.enable_rate_limit {
            return Ok(true);
        }

        if let Some(rate_limiter) = &self.rate_limiter {
            Ok(rate_limiter.is_allowed(client_id).await)
        } else {
            Ok(true)
        }
    }

    /// 获取剩余请求数
    pub async fn get_remaining_requests(&self, client_id: &str) -> u32 {
        if let Some(rate_limiter) = &self.rate_limiter {
            rate_limiter.remaining_requests(client_id).await
        } else {
            u32::MAX
        }
    }

    /// 清理过期限流记录
    pub async fn cleanup_rate_limit_records(&self) {
        if let Some(rate_limiter) = &self.rate_limiter {
            rate_limiter.cleanup_expired().await;
        }
    }

    /// 提取客户端ID
    pub fn extract_client_id(headers: &axum::http::HeaderMap, remote_addr: Option<&str>) -> String {
        // 优先使用X-Forwarded-For
        if let Some(forwarded) = headers.get("X-Forwarded-For") {
            if let Ok(forwarded_str) = forwarded.to_str() {
                if let Some(first_ip) = forwarded_str.split(',').next() {
                    return first_ip.trim().to_string();
                }
            }
        }

        // 使用X-Real-IP
        if let Some(real_ip) = headers.get("X-Real-IP") {
            if let Ok(ip_str) = real_ip.to_str() {
                return ip_str.to_string();
            }
        }

        // 使用远程地址
        remote_addr.unwrap_or("unknown").to_string()
    }

    /// 从请求头中提取认证信息
    pub fn extract_auth_method(headers: &HeaderMap) -> Option<AuthMethod> {
        // 检查API密钥
        if let Some(api_key) = headers.get("X-API-Key") {
            if let Ok(key) = api_key.to_str() {
                return Some(AuthMethod::ApiKey(key.to_string()));
            }
        }

        // 检查Authorization头
        if let Some(auth_header) = headers.get("Authorization") {
            if let Ok(auth_str) = auth_header.to_str() {
                if auth_str.starts_with("Bearer ") {
                    let token = auth_str[7..].to_string();
                    return Some(AuthMethod::BearerToken(token));
                } else if auth_str.starts_with("Basic ") {
                    let encoded = &auth_str[6..];
                    if let Ok(decoded) = general_purpose::STANDARD.decode(encoded) {
                        if let Ok(credentials) = String::from_utf8(decoded) {
                            let parts: Vec<&str> = credentials.splitn(2, ':').collect();
                            if parts.len() == 2 {
                                return Some(AuthMethod::BasicAuth {
                                    username: parts[0].to_string(),
                                    password: parts[1].to_string(),
                                });
                            }
                        }
                    }
                }
            }
        }

        None
    }
}

/// 认证中间件
#[derive(Clone)]
pub struct AuthLayer {
    provider: Arc<dyn AuthProvider>,
}

impl AuthLayer {
    pub fn new(provider: Arc<dyn AuthProvider>) -> Self {
        Self { provider }
    }
}

impl<S> Layer<S> for AuthLayer {
    type Service = AuthService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        AuthService {
            inner,
            provider: self.provider.clone(),
        }
    }
}

/// 认证服务
#[derive(Clone)]
pub struct AuthService<S> {
    inner: S,
    provider: Arc<dyn AuthProvider>,
}

impl<S> Service<Request<Body>> for AuthService<S>
where
    S: Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<Body>) -> Self::Future {
        let provider = self.provider.clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // 提取认证信息
            let auth_method = MiddlewareManager::extract_auth_method(req.headers());

            if let Some(method) = auth_method {
                // 执行认证
                match provider.authenticate(method).await {
                    AuthResult::Success(user) => {
                        // 认证成功，将用户信息添加到请求扩展中
                        req.extensions_mut().insert(user);
                        // 继续处理请求
                        inner.call(req).await
                    }
                    AuthResult::Failed(reason) => {
                        // 认证失败，返回401
                        let response = Response::builder()
                            .status(StatusCode::UNAUTHORIZED)
                            .header("Content-Type", "application/json")
                            .body(Body::from(json!({
                                "error": "认证失败",
                                "message": reason
                            }).to_string()))
                            .unwrap();
                        Ok(response)
                    }
                    AuthResult::Required => {
                        // 需要认证，返回401
                        let response = Response::builder()
                            .status(StatusCode::UNAUTHORIZED)
                            .header("Content-Type", "application/json")
                            .header("WWW-Authenticate", "Bearer, Basic, X-API-Key")
                            .body(Body::from(json!({
                                "error": "需要认证",
                                "message": "请提供有效的认证信息"
                            }).to_string()))
                            .unwrap();
                        Ok(response)
                    }
                }
            } else {
                // 没有认证信息，返回401
                let response = Response::builder()
                    .status(StatusCode::UNAUTHORIZED)
                    .header("Content-Type", "application/json")
                    .header("WWW-Authenticate", "Bearer, Basic, X-API-Key")
                    .body(Body::from(json!({
                        "error": "需要认证",
                        "message": "请提供认证信息"
                    }).to_string()))
                    .unwrap();
                Ok(response)
            }
        })
    }
}

/// 请求日志中间件
#[derive(Clone)]
pub struct RequestLoggingLayer;

impl RequestLoggingLayer {
    pub fn new() -> Self {
        Self
    }
}

impl<S> Layer<S> for RequestLoggingLayer {
    type Service = RequestLoggingService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RequestLoggingService { inner }
    }
}

/// 请求日志服务
#[derive(Clone)]
pub struct RequestLoggingService<S> {
    inner: S,
}

impl<S> Service<Request<Body>> for RequestLoggingService<S>
where
    S: Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let start_time = Instant::now();
        let method = request.method().clone();
        let uri = request.uri().clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            let response = inner.call(request).await?;
            let duration = start_time.elapsed();

            tracing::info!(
                method = %method,
                uri = %uri,
                status = %response.status(),
                duration_ms = duration.as_millis(),
                "HTTP请求处理完成"
            );

            Ok(response)
        })
    }
}

/// CORS中间件层
#[derive(Clone)]
pub struct CorsLayer;

impl CorsLayer {
    pub fn new() -> Self {
        Self
    }
}

impl<S> Layer<S> for CorsLayer {
    type Service = CorsService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CorsService { inner }
    }
}

/// CORS服务
#[derive(Clone)]
pub struct CorsService<S> {
    inner: S,
}

impl<S> Service<Request<Body>> for CorsService<S>
where
    S: Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // 处理预检请求
            if request.method() == &axum::http::Method::OPTIONS {
                let response = Response::builder()
                    .status(StatusCode::OK)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                    .header("Access-Control-Allow-Headers", "Content-Type, Authorization")
                    .header("Access-Control-Max-Age", "86400")
                    .body(Body::empty())
                    .unwrap();
                return Ok(response);
            }

            let mut response = inner.call(request).await?;

            // 添加CORS头
            let headers = response.headers_mut();
            headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap());
            headers.insert("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS".parse().unwrap());
            headers.insert("Access-Control-Allow-Headers", "Content-Type, Authorization".parse().unwrap());

            Ok(response)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_middleware_config_default() {
        let config = MiddlewareConfig::default();
        assert!(config.enable_logging);
        assert!(config.enable_cors);
        assert!(!config.enable_auth);
        assert!(!config.enable_rate_limit);
        assert_eq!(config.request_timeout, 30);
    }

    #[test]
    fn test_middleware_manager_creation() {
        let config = MiddlewareConfig::default();
        let manager = MiddlewareManager::new(config.clone());
        assert_eq!(manager.config().enable_logging, config.enable_logging);
    }

    #[test]
    fn test_request_logging_layer_creation() {
        let _layer = RequestLoggingLayer::new();
        // 只是验证创建成功
        assert!(true);
    }

    #[test]
    fn test_cors_layer_creation() {
        let _layer = CorsLayer::new();
        // 只是验证创建成功
        assert!(true);
    }

    #[test]
    fn test_memory_auth_provider_creation() {
        let provider = MemoryAuthProvider::new();
        assert!(!provider.api_keys.is_empty());
        assert!(!provider.users.is_empty());
    }

    #[test]
    fn test_memory_auth_provider_add_api_key() {
        let mut provider = MemoryAuthProvider::new();
        let user = User {
            id: "test".to_string(),
            username: "test".to_string(),
            roles: vec!["user".to_string()],
            permissions: vec!["read".to_string()],
        };

        provider.add_api_key("test-key".to_string(), user.clone());
        assert!(provider.api_keys.contains_key("test-key"));
    }

    #[test]
    fn test_memory_auth_provider_add_user() {
        let mut provider = MemoryAuthProvider::new();
        let user = User {
            id: "test".to_string(),
            username: "test".to_string(),
            roles: vec!["user".to_string()],
            permissions: vec!["read".to_string()],
        };

        provider.add_user("test".to_string(), "password".to_string(), user.clone());
        assert!(provider.users.contains_key("test"));
    }

    #[tokio::test]
    async fn test_memory_auth_provider_api_key_auth() {
        let provider = MemoryAuthProvider::new();

        // 测试有效的API密钥
        let result = provider.authenticate(AuthMethod::ApiKey("admin-key-123".to_string())).await;
        match result {
            AuthResult::Success(user) => {
                assert_eq!(user.username, "admin");
                assert!(user.roles.contains(&"admin".to_string()));
            }
            _ => panic!("应该认证成功"),
        }

        // 测试无效的API密钥
        let result = provider.authenticate(AuthMethod::ApiKey("invalid-key".to_string())).await;
        match result {
            AuthResult::Failed(_) => {}, // 预期结果
            _ => panic!("应该认证失败"),
        }
    }

    #[tokio::test]
    async fn test_memory_auth_provider_basic_auth() {
        let provider = MemoryAuthProvider::new();

        // 测试有效的用户名密码
        let result = provider.authenticate(AuthMethod::BasicAuth {
            username: "admin".to_string(),
            password: "admin123".to_string(),
        }).await;
        match result {
            AuthResult::Success(user) => {
                assert_eq!(user.username, "admin");
            }
            _ => panic!("应该认证成功"),
        }

        // 测试无效的密码
        let result = provider.authenticate(AuthMethod::BasicAuth {
            username: "admin".to_string(),
            password: "wrong-password".to_string(),
        }).await;
        match result {
            AuthResult::Failed(_) => {}, // 预期结果
            _ => panic!("应该认证失败"),
        }

        // 测试不存在的用户
        let result = provider.authenticate(AuthMethod::BasicAuth {
            username: "nonexistent".to_string(),
            password: "password".to_string(),
        }).await;
        match result {
            AuthResult::Failed(_) => {}, // 预期结果
            _ => panic!("应该认证失败"),
        }
    }

    #[tokio::test]
    async fn test_memory_auth_provider_authorization() {
        let provider = MemoryAuthProvider::new();

        // 测试管理员权限
        let admin_user = User {
            id: "admin".to_string(),
            username: "admin".to_string(),
            roles: vec!["admin".to_string()],
            permissions: vec!["*".to_string()],
        };

        let result = provider.authorize(&admin_user, "/api/users", "read").await;
        match result {
            AuthzResult::Allowed => {}, // 预期结果
            _ => panic!("管理员应该有权限"),
        }

        // 测试普通用户权限
        let user = User {
            id: "user".to_string(),
            username: "user".to_string(),
            roles: vec!["user".to_string()],
            permissions: vec!["read".to_string()],
        };

        let result = provider.authorize(&user, "/api/users", "read").await;
        match result {
            AuthzResult::Denied(_) => {}, // 预期结果（简化实现中普通用户没有权限）
            _ => panic!("普通用户应该没有权限"),
        }
    }

    #[test]
    fn test_extract_auth_method_api_key() {
        let mut headers = HeaderMap::new();
        headers.insert("X-API-Key", "test-key".parse().unwrap());

        let auth_method = MiddlewareManager::extract_auth_method(&headers);
        match auth_method {
            Some(AuthMethod::ApiKey(key)) => assert_eq!(key, "test-key"),
            _ => panic!("应该提取到API密钥"),
        }
    }

    #[test]
    fn test_extract_auth_method_bearer_token() {
        let mut headers = HeaderMap::new();
        headers.insert("Authorization", "Bearer test-token".parse().unwrap());

        let auth_method = MiddlewareManager::extract_auth_method(&headers);
        match auth_method {
            Some(AuthMethod::BearerToken(token)) => assert_eq!(token, "test-token"),
            _ => panic!("应该提取到Bearer Token"),
        }
    }

    #[test]
    fn test_extract_auth_method_basic_auth() {
        let mut headers = HeaderMap::new();
        let credentials = general_purpose::STANDARD.encode("user:pass");
        headers.insert("Authorization", format!("Basic {}", credentials).parse().unwrap());

        let auth_method = MiddlewareManager::extract_auth_method(&headers);
        match auth_method {
            Some(AuthMethod::BasicAuth { username, password }) => {
                assert_eq!(username, "user");
                assert_eq!(password, "pass");
            }
            _ => panic!("应该提取到Basic Auth"),
        }
    }

    #[test]
    fn test_extract_auth_method_none() {
        let headers = HeaderMap::new();
        let auth_method = MiddlewareManager::extract_auth_method(&headers);
        assert!(auth_method.is_none());
    }

    #[test]
    fn test_password_hashing() {
        let password = "test123";
        let hash1 = MemoryAuthProvider::hash_password(password);
        let hash2 = MemoryAuthProvider::hash_password(password);

        // 相同密码应该产生相同哈希
        assert_eq!(hash1, hash2);

        // 验证密码
        assert!(MemoryAuthProvider::verify_password(password, &hash1));
        assert!(!MemoryAuthProvider::verify_password("wrong", &hash1));
    }

    #[tokio::test]
    async fn test_rate_limiter_basic_functionality() {
        let config = RateLimitConfig {
            requests_per_minute: 10,
            burst_capacity: 5,
            window_size: 60,
        };
        let rate_limiter = RateLimiter::new(config);

        // 测试初始状态
        assert!(rate_limiter.is_allowed("client1").await);
        assert_eq!(rate_limiter.remaining_requests("client1").await, 9);

        // 测试多次请求
        for i in 2..=10 {
            assert!(rate_limiter.is_allowed("client1").await);
            assert_eq!(rate_limiter.remaining_requests("client1").await, 10 - i);
        }

        // 测试超过限制
        assert!(!rate_limiter.is_allowed("client1").await);
        assert_eq!(rate_limiter.remaining_requests("client1").await, 0);
    }

    #[tokio::test]
    async fn test_rate_limiter_different_clients() {
        let config = RateLimitConfig {
            requests_per_minute: 5,
            burst_capacity: 2,
            window_size: 60,
        };
        let rate_limiter = RateLimiter::new(config);

        // 不同客户端应该有独立的限制
        for _ in 0..5 {
            assert!(rate_limiter.is_allowed("client1").await);
            assert!(rate_limiter.is_allowed("client2").await);
        }

        // 两个客户端都应该达到限制
        assert!(!rate_limiter.is_allowed("client1").await);
        assert!(!rate_limiter.is_allowed("client2").await);
    }

    #[tokio::test]
    async fn test_middleware_manager_rate_limit() {
        let mut config = MiddlewareConfig::default();
        config.enable_rate_limit = true;
        config.rate_limit_config = Some(RateLimitConfig {
            requests_per_minute: 3,
            burst_capacity: 1,
            window_size: 60,
        });

        let manager = MiddlewareManager::new(config);

        // 测试限流检查
        assert!(manager.check_rate_limit("test_client").await.unwrap());
        assert!(manager.check_rate_limit("test_client").await.unwrap());
        assert!(manager.check_rate_limit("test_client").await.unwrap());
        assert!(!manager.check_rate_limit("test_client").await.unwrap());

        // 测试剩余请求数
        assert_eq!(manager.get_remaining_requests("test_client").await, 0);
    }

    #[test]
    fn test_extract_client_id() {
        let mut headers = axum::http::HeaderMap::new();

        // 测试X-Forwarded-For
        headers.insert("X-Forwarded-For", "192.168.1.1, 10.0.0.1".parse().unwrap());
        assert_eq!(MiddlewareManager::extract_client_id(&headers, None), "192.168.1.1");

        // 测试X-Real-IP
        headers.clear();
        headers.insert("X-Real-IP", "192.168.1.2".parse().unwrap());
        assert_eq!(MiddlewareManager::extract_client_id(&headers, None), "192.168.1.2");

        // 测试远程地址
        headers.clear();
        assert_eq!(MiddlewareManager::extract_client_id(&headers, Some("192.168.1.3")), "192.168.1.3");

        // 测试默认值
        assert_eq!(MiddlewareManager::extract_client_id(&headers, None), "unknown");
    }
}
